//
//  AttachViewController.m
//  ExchangeClient
//
//  Created by Антон on 19.12.12.
//  Copyright (c) 2012 Сураева Яна. All rights reserved.
//

#import "AttachViewController.h"
#import "PDFViewer.h"

@interface AttachViewController ()

@end

@implementation AttachViewController
@synthesize scrollView, requestHandlerInstance, mail;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [self initData];
    /*NSDictionary *temp = [requestInstance getAttachmentWithID:@"AAANAHMyQGRpZ2Rlcy5jb20ARgAAAAAAIVkFkxwE/U6oKVqAurvPrwcAXtbn1WidSku/aYPp03dwPAAAAAsdMwAAXtbn1WidSku/aYPp03dwPAAAERzX0gAAAQYABAAFAAAA"];
     if ([[temp valueForKey:@"Name"] hasSuffix:@".pdf"]) {
     
     NSData* data = [self dataWithBase64EncodedString:[temp valueForKey:@"Content"]];
     NSString *path = [self dataFilePath:[temp valueForKey:@"Name"]];
     [data writeToFile:path atomically:YES];
     NSLog(@"%@",path);
     
     }*/
/*    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory= [paths objectAtIndex:0];
    NSString *path= [documentsDirectory stringByAppendingPathComponent:@"729e24c112fa406a832e409175c98ccb.pdf"];
    [PDFViewer initing:scrollView :path];
    [scrollView reloadInputViews];
 */   
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc
{
    [scrollView release];
    [super dealloc];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
	return [self.scrollView.subviews objectAtIndex:0];
}


-(void)initData{
    NSUInteger ind;
    for (ind=0; ind<[mail.attachments count]; ind++) {
        
    
        
//    NSDictionary *temp = [requestHandlerInstance getAttachmentWithID:mail.itemID];
    NSDictionary *temp = [requestHandlerInstance getAttachmentWithID:[mail.attachments objectAtIndex:ind]];
        if ([[temp valueForKey:@"Name"] hasSuffix:@".pdf"]) {
     
     NSData* data = [self dataWithBase64EncodedString:[temp valueForKey:@"Content"]];
     NSString *path = [self dataFilePath:[temp valueForKey:@"Name"]];
     [data writeToFile:path atomically:YES];
     NSLog(@"%@",path);
         NSLog(@"hihi");
     }
     else{
        // NSString *path = [self dataFilePath:[temp valueForKey:@"Name"]];

         NSLog(@"%@",[temp valueForKey:@"Name"]);
         NSLog(@"haha");
     }
     }

}

- (NSString *)dataFilePath:(NSString *)name {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentsPath = [documentsDirectory
                               stringByAppendingPathComponent:name];
    return documentsPath;
    
}

- (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    const char lookup[] =
    {
        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 62, 99, 99, 99, 63,
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 99, 99, 99, 99, 99, 99,
        99,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 99, 99, 99, 99, 99,
        99, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 99, 99, 99, 99, 99
    };
    
    NSData *inputData = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    long long inputLength = [inputData length];
    const unsigned char *inputBytes = [inputData bytes];
    
    long long maxOutputLength = (inputLength / 4 + 1) * 3;
    NSMutableData *outputData = [NSMutableData dataWithLength:maxOutputLength];
    unsigned char *outputBytes = (unsigned char *)[outputData mutableBytes];
    
    int accumulator = 0;
    long long outputLength = 0;
    unsigned char accumulated[] = {0, 0, 0, 0};
    for (long long i = 0; i < inputLength; i++)
    {
        unsigned char decoded = lookup[inputBytes[i] & 0x7F];
        if (decoded != 99)
        {
            accumulated[accumulator] = decoded;
            if (accumulator == 3)
            {
                outputBytes[outputLength++] = (accumulated[0] << 2) | (accumulated[1] >> 4);
                outputBytes[outputLength++] = (accumulated[1] << 4) | (accumulated[2] >> 2);
                outputBytes[outputLength++] = (accumulated[2] << 6) | accumulated[3];
            }
            accumulator = (accumulator + 1) % 4;
        }
    }
    
    //handle left-over data
    if (accumulator > 0) outputBytes[outputLength] = (accumulated[0] << 2) | (accumulated[1] >> 4);
    if (accumulator > 1) outputBytes[++outputLength] = (accumulated[1] << 4) | (accumulated[2] >> 2);
    if (accumulator > 2) outputLength++;
    
    //truncate data to match actual output length
    outputData.length = outputLength;
    return outputLength? outputData: nil;
}

    @end
